package com.xxwy.springboot.routerfunction.handler;

import com.xxwy.springboot.routerfunction.exception.CheckException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * @author xxwy
 * on 2018/8/17 0017
 */
@Order(-2)
@Component
public class ExceptionHandler implements WebExceptionHandler {

    /**
     * 有错误就会响应这个方法
     * @param serverWebExchange
     * @param throwable
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        response.setStatusCode(HttpStatus.BAD_GATEWAY);
        //返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        String errorMessage = toStr(throwable);
        DataBuffer wrap = response.bufferFactory().wrap(errorMessage.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    private String toStr(Throwable throwable) {
        //已知异常
        if(throwable instanceof CheckException){
            CheckException exception = (CheckException) throwable;

            return exception.getFieldName() + " invalid value " + exception.getFieldValue();

        }
        //未知异常,打印堆栈
        else {
            throwable.printStackTrace();
            return throwable.toString();
        }
    }
}
